package com.softer.chengxin.score.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softer.chengxin.common.domin.*;
import com.softer.chengxin.common.enums.*;
import com.softer.chengxin.common.util.DateFormatUtil;
import com.softer.chengxin.corp.dao.CorpDao;
import com.softer.chengxin.home.dao.MessageDao;
import com.softer.chengxin.home.domin.Message;
import com.softer.chengxin.param.dao.ParamDao;
import com.softer.chengxin.param.dao.ScoreTypeDao;
import com.softer.chengxin.param.entity.ParamVO;
import com.softer.chengxin.param.entity.ScoreType;
import com.softer.chengxin.score.dao.SDManagerDao;
import com.softer.chengxin.score.entity.Credit;
import com.softer.chengxin.score.entity.ScoreComposite;
import com.softer.chengxin.score.entity.ScoreCompositeProvince;
import com.softer.chengxin.score.entity.ScoreDetailVO;
import com.softer.chengxin.score.service.SDManagerService;
import com.softer.chengxin.score.util.ScoreUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * @author wangixnrui
 * @date 2018/10/12
 */
@Service
public class SDManagerServiceImpl implements SDManagerService {

    @Autowired
    private SDManagerDao managerDao;
    @Autowired
    private CorpDao corpDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private ScoreUtil scoreUtil;
    @Autowired
    private ParamDao paramDao;
    @Autowired
    private ScoreTypeDao scoreTypeDao;

    private static final String NON_EXISTENT = "类型不存在";

    /**
     * 查询企业信用年度评价列表 条数
     *
     * @param loginName      登录名
     * @param scoreComposite 查询实体
     * @param page           页码
     * @return 结果
     */
    @Override
    public PageInfo<ScoreComposite> getYearScoreDetail(String loginName, ScoreComposite scoreComposite, Page page) {
        String area = null;
        if (!Common.ADMIN.equals(loginName)) {
            area = corpDao.getDistinct(loginName);
        }
        if (StringUtils.isEmpty(scoreComposite.getYear())) {
            scoreComposite.setYear(DateFormatUtil.getSysYear());
        }
        scoreComposite.setArea(area);
        PageHelper.startPage(page.getPage(), page.getLimit());
        List<ScoreComposite> list = managerDao.getYearScoreDetail(scoreComposite);
        return new PageInfo<>(list);
    }


    /**
     * 获取优良负面信息待审批列表
     *
     * @param loginName 登录名
     * @param infoType  信息种类
     * @param qyName    企业名
     * @param proName   项目名
     * @param state     状态
     * @param page      页码
     * @return 结果
     */
    @Override
    public ManagerPageResult getScoreDetailList(String loginName, Integer infoType, String qyName, String proName, String state, Page page) {
        ManagerPageResult mpr = new ManagerPageResult();
        JsonResult jr = new JsonResult();
        //获取当前登录账号dicCode
        String area = null;
        if (!Common.ADMIN.equals(loginName)) {
            area = corpDao.getDistinct(loginName);
        }
        int count = managerDao.getScoreDetailListCount(infoType, area, qyName, proName, state);
        if (count <= NumberEnum.ZERO.getNum()) {
            return common(mpr, jr);
        }
        List<ScoreDetailVO> list = managerDao.getScoreDetailList(infoType, area, page, qyName, proName, state);
        for (ScoreDetailVO s : list) {
            s.setProjectId(managerDao.findProNameById(s.getProjectId()));
        }
        jr.setDs(list);
        mpr.setJson(jr);
        mpr.setCount(count);
        return mpr;
    }

    /**
     * 获取sp列表
     *
     * @param loginName 登录名
     * @param infoType  信息种类
     * @param qyName    企业名
     * @param proName   项目名
     * @param page      页码
     * @return 结果
     */
    @Override
    public ManagerPageResult getSPList(String loginName, Integer infoType, String qyName, String proName, Page page) {
        ManagerPageResult mpr = new ManagerPageResult();
        JsonResult jr = new JsonResult();
        String state = null;
        String dicCode = managerDao.getDicCodeByLoginName(loginName);
        if (StringUtils.isNotBlank(dicCode)) {
            //3市  4区
            if (dicCode.equals(String.valueOf(NumberEnum.THREE.getNum()))) {
                state = String.valueOf(NumberEnum.NINE.getNum());
            } else if (dicCode.equals(String.valueOf(NumberEnum.FOUR.getNum()))) {
                state = "1,11";
            } else if (dicCode.equals(String.valueOf(NumberEnum.ONE_HUNDRED.getNum()))) {
                state = "1,9,11";
            }
        }
        String area = null;
        if (!Common.ADMIN.equals(loginName)) {
            area = corpDao.getDistinct(loginName);
        }
        int count = managerDao.getScoreDetailListCount(infoType, area, qyName, proName, state);
        if (count <= NumberEnum.ZERO.getNum()) {
            return common(mpr, jr);
        }
        List<ScoreDetailVO> list = managerDao.getScoreDetailList(infoType, area, page, qyName, proName, state);
        for (ScoreDetailVO s : list) {
            s.setProjectId(managerDao.findProNameById(s.getProjectId()));
        }
        jr.setDs(list);
        mpr.setJson(jr);
        mpr.setCount(count);
        return mpr;
    }

    /**
     * 获取负面/优良信息 录入界面 的信息列表
     *
     * @param loginName 登录名
     * @param qyName    企业名
     * @param proName   项目名
     * @param infoType  信息种类
     * @param page      页码
     * @return 结果
     */
    @Override
    public ManagerPageResult getScoreAddList(String loginName, String qyName, String proName, Integer infoType, Page page) {
        ManagerPageResult mpr = new ManagerPageResult();
        JsonResult jr = new JsonResult();
        int count = managerDao.getScoreAddListCount(loginName, qyName, proName, infoType);
        if (count <= NumberEnum.ZERO.getNum()) {
            return common(mpr, jr);
        }
        List<ScoreDetailVO> list = managerDao.getScoreAddList(loginName, qyName, proName, infoType, page);
        for (ScoreDetailVO s : list) {
            s.setProName(managerDao.findProNameById(s.getProjectId()));
        }
        jr.setDs(list);
        mpr.setJson(jr);
        mpr.setCount(count);
        return mpr;
    }

    /**
     * 新增 保存 信息
     *
     * @param scoreDetailVO 实体
     * @return 结果
     */
    @Override
    public CommonResult addScore(ScoreDetailVO scoreDetailVO, String loginName) {
        scoreDetailVO.setAdder(loginName);
        //判断开始时间是否为空
        if (StringUtils.isBlank(scoreDetailVO.getEffectiveBeginTime()) || StringUtils.isBlank(scoreDetailVO.getEffectiveEndDate())) {
            return new CommonResult(ResultEnum.FAIL.getCode(), "有效期限请选择完整！");
        }
        managerDao.addScore(scoreDetailVO);
        if (scoreDetailVO.getId() > NumberEnum.ZERO.getNum()) {
            return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
    }

    /**
     * 修改 保存 信息
     *
     * @param scoreDetailVO 实体
     * @return 结果
     */
    @Override
    public CommonResult update(ScoreDetailVO scoreDetailVO, String loginName) {
        //判断开始时间是否为空
        if (StringUtils.isBlank(scoreDetailVO.getEffectiveBeginTime()) || StringUtils.isBlank(scoreDetailVO.getEffectiveEndDate())) {
            return new CommonResult(ResultEnum.FAIL.getCode(), "有效期限请选择完整！");
        }
        scoreDetailVO.setAdder(loginName);
        int ret = managerDao.update(scoreDetailVO);
        if (ret > NumberEnum.ZERO.getNum()) {
            return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
    }

    /**
     * 删除保存的信息
     *
     * @param id 信息id
     * @return 结果
     */
    @Override
    public CommonResult delete(Integer id) {
        int ret = managerDao.delete(id);
        if (ret > NumberEnum.ZERO.getNum()) {
            return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
    }

    /**
     * 获取该企业 年度 的 得分详细（优良信息，负面信息，基本信息）
     *
     * @param qyName             企业名
     * @param infoType           信息种类
     * @param effectiveBeginTime 公示开始时间
     * @param effectiveEndTime   公示结束时间
     * @param corpId             企业id
     * @param year               年度
     * @param loginName          登录名
     * @param page               页码
     * @return 结果集
     */
    @Override
    public ManagerPageResult getScoreDetailByYear(String loginName, String qyName, Integer infoType, String effectiveBeginTime, String effectiveEndTime, Integer corpId, String year, Page page) {
        ManagerPageResult mpr = new ManagerPageResult();
        JsonResult jr = new JsonResult();
        String area = null;
        if (!Common.ADMIN.equals(loginName)) {
            area = corpDao.getDistinct(loginName);
        }
        int count = managerDao.getScoreDetailByYearCount(area, qyName, infoType, effectiveBeginTime, effectiveEndTime, corpId, year);
        if (count <= NumberEnum.ZERO.getNum()) {
            return common(mpr, jr);
        }
        List<ScoreDetailVO> list = managerDao.getScoreDetailByYear(area, qyName, infoType, effectiveBeginTime, effectiveEndTime, corpId, year, page);
        jr.setDs(list);
        mpr.setJson(jr);
        mpr.setCount(count);
        return mpr;
    }

    /**
     * 通过id获取得分详细信息
     *
     * @param id id
     * @return 结果
     */
    @Override
    public ScoreDetailVO getDetailScore(Integer id) {

        return managerDao.getDetailScore(id);
    }

    /**
     * 获取变更信息列表
     *
     * @param page      页码
     * @param qyName    企业名
     * @param proName   项目名
     * @param infoType  信息种类
     * @param loginName 登录名
     * @return 结果
     */
    @Override
    public ManagerPageResult getBianGengList(String loginName, Page page, String qyName, String proName, Integer infoType) {
        ManagerPageResult mpr = new ManagerPageResult();
        JsonResult jr = new JsonResult();
        String area = null;
        if (!Common.ADMIN.equals(loginName)) {
            area = corpDao.getDistinct(loginName);
        }
        //获取当前登录账号dicCode
        String dicCode = managerDao.getDicCodeByLoginName(loginName);
        //默认给个不存在的状态
        String state = "999";
        if (dicCode.equals(String.valueOf(NumberEnum.FOUR.getNum()))) {
            //区管理账号
            state = "4,12";
        } else if (dicCode.equals(String.valueOf(NumberEnum.THREE.getNum()))) {
            //市管理账号
            state = String.valueOf(NumberEnum.TEN.getNum());
        } else if (dicCode.equals(String.valueOf(NumberEnum.ONE_HUNDRED.getNum()))) {
            //市管理账号
            state = String.valueOf("4,10,12");
        }
        Integer count = managerDao.getBianGengListCount(infoType, qyName, proName, loginName, state, area);
        if (count <= NumberEnum.ZERO.getNum()) {
            return common(mpr, jr);
        }
        List<ScoreDetailVO> list = managerDao.getBianGengList(infoType, page, qyName, proName, loginName, state, area);
        mpr.setCount(count);
        jr.setDs(list);
        mpr.setJson(jr);
        return mpr;
    }

    /**
     * 查询省平台推送的
     * 企业信用年度评价列表
     *
     * @param scoreComposite 查询实体
     * @param page           页码
     * @param loginName      登录人
     * @return 结果
     */
    @Override
    public PageInfo<ScoreCompositeProvince> getYearScoreDetailFromProvince(String loginName, ScoreComposite scoreComposite, Page page) {
        setScoreComposite(loginName, scoreComposite);
        PageHelper.startPage(page.getPage(), page.getLimit());
        List<ScoreCompositeProvince> list = managerDao.getYearScoreDetailFromProvince(scoreComposite);
        return new PageInfo<>(list);
    }

    /**
     * 查询企业信用分数明细
     *
     * @param id 企业Id
     * @return 信用分数明细
     */
    @Override
    public Credit getCredit(Integer id) {
        Credit credit = managerDao.getCredit(id, DateFormatUtil.getSysYear());
        //查询优良信息集合
        List<Map> excellentList = managerDao.getEffectiveList(id, ScoreTypeEnum.EXCELLENT.getType());
        credit.setExcellentList(excellentList);
        //查询不良信息集合
        List<Map> negativeList = managerDao.getEffectiveList(id, ScoreTypeEnum.NEGATIVE.getType());
        credit.setNegativeList(negativeList);
        credit.setNegativeScore(new BigDecimal(-1).multiply(credit.getNegativeScore()));
        return credit;
    }

    private void setScoreComposite(String loginName, ScoreComposite scoreComposite) {
        String area = null;
        if (!Common.ADMIN.equals(loginName)) {
            area = corpDao.getDistinct(loginName);
        }
        if (StringUtils.isEmpty(scoreComposite.getYear())) {
            scoreComposite.setYear(DateFormatUtil.getSysYear());
        }
        scoreComposite.setArea(area);
    }

    public ManagerPageResult common(ManagerPageResult mpr, JsonResult jr) {
        jr.setDs(new ArrayList());
        mpr.setJson(jr);
        mpr.setCount(NumberEnum.ZERO.getNum());
        return mpr;
    }

    /**
     * 删除负面/优良信息
     *
     * @param loginName 登录名（判断账号级别）
     * @param id        信息id
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult delete(String loginName, Integer id) {
        int roleId = managerDao.getUserRoleId(loginName);
        if (roleId == NumberEnum.THREE.getNum() || roleId == NumberEnum.ONE.getNum()) {
            Integer corpId = managerDao.getCorpId(id);
            ScoreDetailVO sd = managerDao.findScoreDetailById(id);
            int ret = managerDao.deleteScore(id);
            if (ret > NumberEnum.ZERO.getNum()) {
                //重新计算分数
                scoreUtil.updateRecord(corpId);
                if (sd.getInfoType() != null && sd.getState() != null && sd.getCorpId() != null) {
                    addMsg(sd.getInfoType(), sd.getState(), loginName, sd.getCorpId());
                }
                return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
            }
            return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), Common.NO_AUTHORITY);
    }

    /**
     * 新增  保存并公示  信息
     *
     * @param scoreDetailVO 参数
     * @param loginName     登录名
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult addAndPublicity(ScoreDetailVO scoreDetailVO, String loginName) {
        if (scoreDetailVO.getInfoType() == null || scoreDetailVO.getState() == null || scoreDetailVO.getCorpId() == null) {
            return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
        }
        //判断开始时间是否为空
        if (StringUtils.isBlank(scoreDetailVO.getEffectiveBeginTime()) || StringUtils.isBlank(scoreDetailVO.getEffectiveEndDate())) {
            return new CommonResult(ResultEnum.FAIL.getCode(), "有效期限请选择完整！");
        }
        //计算相差的时间
        ParamVO param = getParam(scoreDetailVO.getInfoType());
        if (param == null) {
            return new CommonResult(ResultEnum.FAIL.getCode(), NON_EXISTENT);
        }
        CommonResult result = dealTime(scoreDetailVO.getState(), scoreDetailVO.getEffectiveBeginTime(), param);
        if (ResultEnum.FAIL.getCode() == result.getData()) {
            return result;
        }
        scoreDetailVO.setAdder(loginName);
        scoreDetailVO.setApproverTime(DateFormatUtil.getNow());
        //获取当前用户的dicCode
        String dicCode = managerDao.getDicCodeByLoginName(loginName);
        if (StringUtils.isBlank(dicCode)) {
            return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
        }
        //如果为区管理账号
        if (dicCode.equals(String.valueOf(NumberEnum.FOUR.getNum()))) {
            scoreDetailVO.setState(NumberEnum.NINE.getNum());
            managerDao.addScore(scoreDetailVO);
            if (scoreDetailVO.getId() > NumberEnum.ZERO.getNum()) {
                return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
            }
            return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
        }
        managerDao.addScore(scoreDetailVO);
        if (scoreDetailVO.getId() > NumberEnum.ZERO.getNum()) {
            //公示结束日期
            Date publicEnd = getPublicEnd(param);
            int ret = managerDao.publicity(loginName, scoreDetailVO.getId(), publicEnd);
            if (ret > NumberEnum.ZERO.getNum()) {
                //重新计算企业分数
                scoreUtil.updateRecord(scoreDetailVO.getCorpId());
                //新增通知消息
                addMsg(scoreDetailVO.getInfoType(), scoreDetailVO.getState(), loginName, scoreDetailVO.getCorpId());
                return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
            }
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
    }

    /**
     * 计算 选择的时间是否符合参数设置
     *
     * @param state 审核状态
     * @param time  选择的时间
     * @param param 参数时间
     * @return 计算结果
     */
    private CommonResult dealTime(Integer state, String time, ParamVO param) {
        if (NumberEnum.TWO.getNum().equals(state)) {
            LocalDate parse = LocalDate.parse(time);
            long value = NumberEnum.ZERO.getNum();
            String unit = "";
            if (UnitEnum.YEAR.getUnit().equals(param.getUnit())) {
                value = LocalDate.now().until(parse, ChronoUnit.YEARS);
                unit = "年";
            } else if (UnitEnum.MONTH.getUnit().equals(param.getUnit())) {
                value = LocalDate.now().until(parse, ChronoUnit.MONTHS);
                unit = "月";
            } else if (UnitEnum.DAY.getUnit().equals(param.getUnit())) {
                value = LocalDate.now().until(parse, ChronoUnit.DAYS);
                unit = "天";
            }
            if (value < Integer.parseInt(param.getParamValue())) {
                StringBuilder msg = new StringBuilder(6);
                msg.append("公示期最少").append(param.getParamValue()).append(unit).append(",请选择").append(param.getParamValue()).append(unit).append("后的时间！");
                return new CommonResult(ResultEnum.FAIL.getCode(), msg.toString());
            }
        }
        return CommonResult.response(NumberEnum.ONE.getNum());
    }

    /**
     * 公示
     *
     * @param loginName 登录名
     * @param id        id
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult publicity(String loginName, Integer id) {
        ScoreDetailVO sd = managerDao.findScoreDetailById(id);
        if (sd == null) {
            return new CommonResult(ResultEnum.FAIL.getCode(), Common.RECORD_NOT_EXIST);
        }
        if (sd.getInfoType() == null) {
            return new CommonResult(ResultEnum.FAIL.getCode(), Common.PLEASE_INTRODUCTION_INFO_TYPE);
        }
        //获取当前用户的dicCode
        String dicCode = managerDao.getDicCodeByLoginName(loginName);
        if (StringUtils.isBlank(dicCode)) {
            return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
        }
        if (dicCode.equals(String.valueOf(NumberEnum.FOUR.getNum()))) {
            //如果为区管理账号
            int ret = managerDao.spNo(id, NumberEnum.NINE.getNum(), sd.getRemark(), loginName, null, null, null);
            if (ret > NumberEnum.ZERO.getNum()) {
                return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
            }
            return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
        }
        //公示结束日期,同生效开始时间
        ParamVO param = getParam(sd.getInfoType());
        if (param == null) {
            return new CommonResult(ResultEnum.FAIL.getCode(), NON_EXISTENT);
        }
        Date publicEnd = getPublicEnd(param);
        int ret = managerDao.publicity(loginName, id, publicEnd);
        if (ret > NumberEnum.ZERO.getNum()) {
            //新增通知消息
            addMsg(sd.getInfoType(), NumberEnum.TWO.getNum(), loginName, sd.getCorpId());
            //重新计算分数
            scoreUtil.updateRecord(sd.getCorpId());
            return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
    }

    /**
     * 审批优良/负面信息
     *
     * @param loginName          登录名
     * @param id                 数据id
     * @param corpId             企业id
     * @param score              得分
     * @param scoreTypeId        得分类型id
     * @param effectiveBeginTime 生效开始时间
     * @param effectiveEndTime   生效结束时间
     * @param remark             备注
     * @param state              状态
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized CommonResult sp(String loginName, Integer id, Integer corpId,
                                        Integer scoreTypeId, String score,
                                        String effectiveBeginTime, String effectiveEndTime,
                                        String remark, Integer state, String backType, Integer scoreTypeDetailId) {

        //获取当前数据的详细信息
        ScoreDetailVO scoreDetail = managerDao.findScoreDetailById(id);
        //判断这条数据是否已被其他同级用户操作过
        if (scoreDetail.getState() != null) {
            //如果状态不为1、9、11,则表示该信息已经被处理
            if (!scoreDetail.getState().equals(NumberEnum.ONE.getNum()) && !scoreDetail.getState().equals(NumberEnum.NINE.getNum()) && !scoreDetail.getState().equals(NumberEnum.ELEVEN.getNum())) {
                return new CommonResult(ResultEnum.FAIL.getCode(), "该记录已经被处理");
            }
        } else {
            return new CommonResult(ResultEnum.FAIL.getCode(), "系统繁忙，请稍后重试");
        }
        //审核失败
        if (state.equals(NumberEnum.THREE.getNum())) {
            //判断回退位置 backType backType   1主管   2企业
            if (String.valueOf(NumberEnum.ONE.getNum()).equals(backType)) {
                state = NumberEnum.ELEVEN.getNum();
            }
            //审核失败
            int ret = managerDao.spNo(id, state, remark, loginName, null, null, null);
            if (ret > NumberEnum.ZERO.getNum()) {
                addMsg(scoreDetail.getInfoType(), Common.THREE, loginName, scoreDetail.getCorpId());
                return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
            }
            return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
        } else if (state.equals(NumberEnum.TWO.getNum())) {
            return approve(loginName, id, scoreTypeId, score, effectiveBeginTime, effectiveEndTime, remark, state, scoreDetail, scoreTypeDetailId, corpId);
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
    }

    /**
     * 审批通过
     *
     * @return CommonResult
     */
    private CommonResult approve(String loginName, Integer id,
                                 Integer scoreTypeId, String score,
                                 String effectiveBeginTime, String effectiveEndTime,
                                 String remark, Integer state, ScoreDetailVO scoreDetail, Integer scoreTypeDetailId, Integer corpId) {
        //获取当前用户的dicCode
        String dicCode = managerDao.getDicCodeByLoginName(loginName);
        if (StringUtils.isBlank(dicCode)) {
            return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
        }
        //判断开始时间是否为空
        if (StringUtils.isBlank(effectiveBeginTime) || StringUtils.isBlank(effectiveEndTime)) {
            return new CommonResult(ResultEnum.FAIL.getCode(), "有效期限请选择完整！");
        }
        //查询当前是优良还是负面审批
        ScoreType scoreType = scoreTypeDao.getScoreType(scoreTypeId);
        if (scoreType == null) {
            return new CommonResult(ResultEnum.FAIL.getCode(), "分数类型错误");
        }
        ParamVO param = getParam(scoreType.getType());
        if (param == null) {
            return new CommonResult(ResultEnum.FAIL.getCode(), NON_EXISTENT);
        }
        if (!NumberEnum.NINE.getNum().equals(scoreDetail.getState())) {
            //市审核中时，不需要计算相差的时间，其他审核需要计算相差的时间
            CommonResult result = dealTime(state, effectiveBeginTime, param);
            if (ResultEnum.FAIL.getCode() == result.getData()) {
                return result;
            }
        }

        //如果区级账号，判断开始时间是否为空，开始时间需要大于当前时间+10天
        if (dicCode.equals(String.valueOf(NumberEnum.FOUR.getNum()))) {
            state = NumberEnum.NINE.getNum();
        } else if (dicCode.equals(String.valueOf(NumberEnum.THREE.getNum())) || dicCode.equals(String.valueOf(NumberEnum.ONE_HUNDRED.getNum()))) {
            state = NumberEnum.TWO.getNum();
        }
        //审核标记
        int ret = managerDao.sp(id, score, scoreTypeId, effectiveBeginTime, effectiveEndTime, remark, loginName, state, scoreTypeDetailId);
        if (ret > Integer.parseInt(Common.ZERO)) {
            addMsg(scoreDetail.getInfoType(), NumberEnum.TWO.getNum(), loginName, scoreDetail.getCorpId());
            //重新计算企业分数
            scoreUtil.updateRecord(corpId);
            return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
    }


    /**
     * 变更优良/负面信息
     *
     * @param scoreDetailVO 参数
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult biangeng(ScoreDetailVO scoreDetailVO, String loginName, String backType) {
        ScoreDetailVO scoreDetail = managerDao.findScoreDetailById(scoreDetailVO.getId());
        if (scoreDetail.getState() != null) {
            if (!scoreDetail.getState().equals(NumberEnum.FOUR.getNum()) && !scoreDetail.getState().equals(NumberEnum.TEN.getNum()) && !scoreDetail.getState().equals(NumberEnum.TWELVE.getNum())) {
                return new CommonResult(ResultEnum.FAIL.getCode(), "该记录已经被处理");
            }
        } else {
            return new CommonResult(ResultEnum.FAIL.getCode(), "系统繁忙，请稍后重试");
        }
        //如果审批不通过
        if (scoreDetailVO.getState().equals(NumberEnum.FIVE.getNum())) {
            //获取当前用户的dicCode
            String dicCode = managerDao.getDicCodeByLoginName(loginName);
            if (StringUtils.isBlank(dicCode)) {
                return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
            }
            //如果为区管理账号
            if (dicCode.equals(String.valueOf(NumberEnum.FOUR.getNum()))) {
                int ret = managerDao.spNo(scoreDetailVO.getId(), NumberEnum.TEN.getNum(), scoreDetailVO.getRemark(), loginName, scoreDetailVO.getSsnr(), String.valueOf(scoreDetailVO.getScore()), scoreDetailVO.getScoreTypeId());
                if (ret > NumberEnum.ZERO.getNum()) {
                    return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
                }
                return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
            }
        }
        scoreDetailVO.setScore(scoreDetailVO.getScore().abs());
        //修改企业得分信息   backType   1主管   2企业
        if (String.valueOf(NumberEnum.ONE.getNum()).equals(backType)) {
            scoreDetailVO.setState(NumberEnum.TWELVE.getNum());
        }
        int num = managerDao.biangeng(scoreDetailVO);
        if (!scoreDetailVO.getState().equals(NumberEnum.SIX.getNum())) {
            //如果审批通过则重新计算并修改该企业的得分信息
            scoreUtil.updateRecord(scoreDetailVO.getCorpId());
        }
        if (num > Integer.parseInt(Common.ZERO)) {
            //增加通知消息
            if (scoreDetail.getInfoType() != null && scoreDetail.getState() != null && scoreDetail.getCorpId() != null) {
                addMsg(scoreDetail.getInfoType(), scoreDetailVO.getState(), loginName, scoreDetail.getCorpId());
            }
            return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
    }

    /**
     * 新增消息
     *
     * @param infoType  消息类型（1优良信息，2负面信息，3严重负面信息）
     * @param state     消息状态 (0-黑名单失效，1-黑名单生效，2-公示，3-审核不通过，
     *                  5-申诉成功，6-申诉失败，8-失效)
     * @param loginName 登录名
     * @param corpId    企业id
     */
    public void addMsg(Integer infoType, Integer state, String loginName, Integer corpId) {
        Message message = new Message();
        message.setType(infoType);
        if (infoType == InfoTypeEnum.EXCELLENT.getCode() && state == StateEnum.LOSE_EFFECT.getCode()) {
            //优良信息失效 infoType 1，state 8，url 优良查询界面
            message.setTitle(MessageEnum.IS_LOSE_YOULIANG.getMsg() + LocalDate.now());
            message.setUrl(UrlEnum.QUERY_GOOD_INFO.getUrl());
        } else if (infoType == InfoTypeEnum.EXCELLENT.getCode() && state == StateEnum.PASS_THROUGH.getCode()) {
            //优良信息审核通过/公示  infoType 1，state 2，url 优良录入界面
            message.setTitle(MessageEnum.IS_PASS_YOULIANG.getMsg() + LocalDate.now());
            message.setUrl(UrlEnum.ADD_GOOD_INFO.getUrl());
        } else if (infoType == InfoTypeEnum.EXCELLENT.getCode() && state == StateEnum.NOT_THROUGH.getCode()) {
            //优良信息审核不通过  infoType 1，state 3，url 优良查询界面
            message.setTitle(MessageEnum.IS_NO_PASS_YOULIANG.getMsg() + LocalDate.now());
            message.setUrl(UrlEnum.QUERY_GOOD_INFO.getUrl());
        } else if (infoType == InfoTypeEnum.EXCELLENT.getCode() && state == StateEnum.APPEAL_SUCCESS.getCode()) {
            //优良信息申诉通过  infoType 1，state 5，url 优良查询界面
            message.setTitle(MessageEnum.GOOD_INFO_APPEAL.getMsg() + LocalDate.now());
            message.setUrl(UrlEnum.QUERY_GOOD_INFO.getUrl());
        } else if (infoType == InfoTypeEnum.EXCELLENT.getCode() && state == StateEnum.APPEAL_FAIL.getCode()) {
            //优良信息申诉未通过  infoType 1，state 6，url 优良查询界面
            message.setTitle(MessageEnum.GOOD_INFO_NO_APPEAL.getMsg() + LocalDate.now());
            message.setUrl(UrlEnum.QUERY_GOOD_INFO.getUrl());
        } else if (infoType == InfoTypeEnum.NEGATIVE.getCode() && state == StateEnum.LOSE_EFFECT.getCode()) {
            //负面信息审核失效  infoType 2，state 8，url 负面查询界面
            message.setTitle(MessageEnum.IS_LOSE_FUMIAN.getMsg() + LocalDate.now());
            message.setUrl(UrlEnum.QUERY_BAD_INFO.getUrl());
        } else if (infoType == InfoTypeEnum.NEGATIVE.getCode() && state == StateEnum.PASS_THROUGH.getCode()) {
            //负面信息审核通过/公示  infoType 2，state 2，url 负面录入界面
            message.setTitle(MessageEnum.IS_PASS_FUMIAN.getMsg() + LocalDate.now());
            message.setUrl(UrlEnum.ADD_BAD_INFO.getUrl());
        } else if (infoType == InfoTypeEnum.NEGATIVE.getCode() && state == StateEnum.NOT_THROUGH.getCode()) {
            //负面信息审核不通过  infoType 2，state 3，url 负面查询界面
            message.setTitle(MessageEnum.IS_NO_PASS_FUMIAN.getMsg() + LocalDate.now());
            message.setUrl(UrlEnum.QUERY_BAD_INFO.getUrl());
        } else if (infoType == InfoTypeEnum.NEGATIVE.getCode() && state == StateEnum.APPEAL_SUCCESS.getCode()) {
            //负面信息申诉通过  infoType 2，state 5，url 负面查询界面
            message.setTitle(MessageEnum.BAD_INFO_APPEAL.getMsg() + LocalDate.now());
            message.setUrl(UrlEnum.QUERY_BAD_INFO.getUrl());
        } else if (infoType == InfoTypeEnum.NEGATIVE.getCode() && state == StateEnum.APPEAL_FAIL.getCode()) {
            //负面信息申诉未通过  infoType 2，state 6，url 负面查询界面
            message.setTitle(MessageEnum.BAD_INFO_NO_APPEAL.getMsg() + LocalDate.now());
            message.setUrl(UrlEnum.QUERY_BAD_INFO.getUrl());
        } else if (infoType == InfoTypeEnum.SERIOUS_NEGATIVE.getCode() && state == StateEnum.TACK_EFFECT.getCode()) {
            //黑名单生效  infoType 3，state 1，url 黑名单界面
            message.setTitle(MessageEnum.IS_ADD_BLACKLIST.getMsg() + LocalDate.now());
            message.setUrl(UrlEnum.VERY_BAD_INFO.getUrl());
        } else if (infoType == InfoTypeEnum.SERIOUS_NEGATIVE.getCode() && state == StateEnum.LOSE_EFFICACY.getCode()) {
            //黑名单失效  infoType 3，state 0，url 黑名单界面
            message.setTitle(MessageEnum.IS_REMOVE_BLACKLIST.getMsg() + LocalDate.now());
            message.setUrl(UrlEnum.VERY_BAD_INFO.getUrl());
        }
        message.setAdder(loginName);
        message.setCropid(corpId);
        messageDao.addMessage(message);
    }

    /**
     * 查询参数实体
     *
     * @param type 优良1，负面2
     * @return 参数实体
     */
    public ParamVO getParam(int type) {
        ParamVO param = null;
        if (NumberEnum.ONE.getNum().equals(type)) {
            //优良信息申诉有效期
            param = paramDao.getParma(ParamEnum.EXCELLENT_APPEAL.getKey());
        } else if (NumberEnum.TWO.getNum().equals(type)) {
            //负面信息申诉有效期
            param = paramDao.getParma(ParamEnum.NEGATIVE_APPEAL.getKey());
        }
        return param;
    }

    /**
     * 获取公示结束日期
     *
     * @param param
     * @return
     */
    private Date getPublicEnd(ParamVO param) {
        //公示开始日期
        Date publicBegin = new Date();
        Calendar ca = Calendar.getInstance();
        ca.setTime(publicBegin);
        if (UnitEnum.YEAR.getUnit().equals(param.getUnit())) {
            ca.add(Calendar.YEAR, Integer.parseInt(param.getParamValue()));
        } else if (UnitEnum.MONTH.getUnit().equals(param.getUnit())) {
            ca.add(Calendar.MONTH, Integer.parseInt(param.getParamValue()));
        } else if (UnitEnum.DAY.getUnit().equals(param.getUnit())) {
            ca.add(Calendar.DATE, Integer.parseInt(param.getParamValue()));
        }
        return ca.getTime();
    }
}
